package com.gome.ocean.service.yugong.impl;

import java.net.URL;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.gome.ocean.common.constants.YugongContants;
import com.gome.ocean.common.exception.YugongRemoteInvokeException;
import com.gome.ocean.common.utils.AddressUtils;
import com.gome.ocean.common.utils.HttpClientUtil;
import com.gome.ocean.dao.model.yugong.YgManagerBO;
import com.gome.ocean.dao.model.yugong.YgTaskBO;
import com.gome.ocean.dao.model.yugong.YuGongConfVO;
import com.gome.ocean.dao.yugong.YgTaskDAO;
import com.gome.ocean.service.utils.CmdToolkit;
import com.gome.ocean.service.velocity.VelocityBean;
import com.gome.ocean.service.yugong.YgManagerService;
import com.gome.ocean.service.yugong.YgTaskService;
import com.gome.ocean.service.yugong.YugongService;

@Service
public class YgTaskServiceImpl implements YgTaskService {

    private static final Logger LOG = LoggerFactory.getLogger(YgTaskServiceImpl.class);

    @Autowired
    private YgTaskDAO           ygTaskDAO;
    @Autowired
    private VelocityBean        velocityBean;
    @Autowired
    private YgManagerService    ygManagerService;
    @Autowired
    private YugongService       yugongService;

    @Override
    public boolean insertYgTask(YgTaskBO ygTask) {
        return ygTaskDAO.insertYgTask(ygTask) > 0;
    }

    @Override
    public boolean insertYgTask(YuGongConfVO confVO) {
        YgTaskBO taskBO = new YgTaskBO();
        taskBO.setManagerId(confVO.getManagerId());
        taskBO.setProject(confVO.getProject());
        taskBO.setState("0");
        taskBO.setIsRocketMqTarget(confVO.getIsRocketMqTarget());
        taskBO.setTableName(confVO.getTableName());
        taskBO.setSourceDatasourceId(confVO.getSourceDatasourceId());
        taskBO.setMoveMode(confVO.getMoveMode());
        taskBO.setTargetDatasourceId(confVO.getTargetDatasourceId());
        taskBO.setContext(velocityBean.generateYugongProps(confVO.getConfParams()));
        return ygTaskDAO.insertYgTask(taskBO) == 1;
    }

    @Override
    public boolean removeYgTaskById(Long id) {
        return ygTaskDAO.removeYgTaskById(id) > 0;
    }

    @Override
    public boolean updateYgTask(YgTaskBO ygTask) {
        return ygTaskDAO.updateYgTaskById(ygTask) > 0;
    }

    @Override
    public YgTaskBO findYgTaskBOById(Long id) {
        return ygTaskDAO.findYgTaskById(id);
    }

    @Override
    public Page<YgTaskBO> findYgTaskBOsByTableName(String tableName, Integer pageNum, Integer pageSize) {
        return ygTaskDAO.findYgTaskBOsByTableName(tableName, new RowBounds(pageNum, pageSize));
    }

    @Override
    public Page<YgTaskBO> findAllYgTaskBOs(Integer pageNum, Integer pageSize) {
        return ygTaskDAO.findAllYgTaskBOs(new RowBounds(pageNum, pageSize));
    }

    @Override
    public Page<YgTaskBO> findAllYgTaskBOsByProject(Integer pageNum, Integer pageSize, String project) {
        return ygTaskDAO.findAllYgTaskBOsByProject(new RowBounds(pageNum, pageSize), project);
    }

    @Override
    public Page<YgTaskBO> findAllYgTaskBOsByProjectNames(Integer pageNum, Integer pageSize, List<String> projectNames) {
        return ygTaskDAO.findAllYgTaskBOsByProjectNames(new RowBounds(pageNum, pageSize), projectNames);
    }

    @Override
    public String stopTask(YgManagerBO ygManager, YgTaskBO ygTask) {
        // 判断是否是本机
        if (AddressUtils.isLocalIp(ygManager.getYgIp())) {
            String commond = YugongContants.getYugongStop(ygManager.getYgLocation());
            String result = CmdToolkit.executeCmd(commond);
            if (StringUtils.contains(result, "ok!")) {
                ygManager.setIsOccupy(0); // 更新状态未使用
                ygTask.setState("0"); //未运行
                ygTaskDAO.updateYgTaskById(ygTask);
                ygManagerService.updateYgManagerBO(ygManager);
                LOG.info("yugong local execute stop commond!result:" + result);
                return result;
            } else {
                LOG.error("yugong local execute stop commond is error!");
                return result;
            }
        } else {
            String yuGongpath = YugongContants.getRemoteYugongStopPath(ygManager.getYgIp(), ygTask.getId());
            HttpClientUtil httpClientUtil = new HttpClientUtil();
            try {
                URL url = new URL(yuGongpath);
                HttpGet httpGet = HttpClientUtil.getGetRequest();
                httpGet.setURI(url.toURI());
                return httpClientUtil.executeAndGetWithFailedRetry(httpGet, 6, 1000l);
            } catch (Exception e) {
                LOG.error("执行远程stop命令失败！" + e);
                throw new YugongRemoteInvokeException("执行远程stop命令失败！" + yuGongpath, e);
            }
        }
    }

    @Override
    public String startTask(YgManagerBO ygManager, YgTaskBO ygTask) {
        // 判断是否是本机
        if (AddressUtils.isLocalIp(ygManager.getYgIp())) {
            String ygStartCmd = YugongContants.getYugongStart(ygManager.getYgLocation());
            yugongService.uploadYugongConfig(ygTask);// 将数据库中的配置内容写入配置文件
            String result = CmdToolkit.executeCmd(ygStartCmd);
            if (StringUtils.contains(result, "ok!")) {
                ygManager.setIsOccupy(1); // 更新状态为使用
                ygTask.setState("1"); //运行中
                ygManagerService.updateYgManagerBO(ygManager);
                ygTaskDAO.updateYgTaskById(ygTask);
                LOG.info("yugong local execute start command!result:" + result);
                return result;
            } else {
                LOG.error("yugong local execute start command is error!");
                return result;
            }
        } else {
            String yuGongpath = YugongContants.getRemoteYugongStartPath(ygManager.getYgIp(), ygTask.getId());
            HttpClientUtil httpClientUtil = new HttpClientUtil();
            try {
                URL url = new URL(yuGongpath);
                HttpGet httpGet = HttpClientUtil.getGetRequest();
                httpGet.setURI(url.toURI());
                return httpClientUtil.executeAndGetWithFailedRetry(httpGet, 6, 1000l);
            } catch (Exception e) {
                LOG.error("执行远程start命令失败！" + e);
                throw new YugongRemoteInvokeException("执行远程start命令失败！" + yuGongpath, e);
            }
        }
    }

    @Override
    public String tailTaskInfo(YgTaskBO ygTask) {
        // YgManagerBO ygManagerBO =
        // ygManagerService.findYgManagerBOById(ygTaskBO.getManagerId());
        // if (ygManagerBO == null) {
        // LOG.error("yugong manager is error!managerId:" +
        // ygTaskBO.getManagerId());
        // return StringUtils.EMPTY;
        // }
        // try {
        // ShellBuilder shellBuilder = ShellBuilder.newSehll()
        // .withHost(ygManagerBO.getYgIp())
        // .withUser(ygManagerBO.getYgUser())
        // .withPasswd(ygManagerBO.getYgPwd())
        // .build();
        // StringBuffer commond = new StringBuffer();
        // commond.append("tail -f ")
        // .append(ygManagerBO.getYgLocation())
        // .append(YugongContants.YUGONG_LOGS)
        // .append("/*/table.log");
        // String result = shellBuilder.execCmd(commond.toString());
        // return result;
        // } catch (JSchException e) {
        // LOG.error("yugong execute commond is error!YgTaskBO:" + ygTaskBO);
        // return StringUtils.EMPTY;
        // }
        return null;
    }
}
